package com.esayread.ui.bookshelf

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Book
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import coil.compose.AsyncImage
import coil.request.ImageRequest
import java.io.File
import com.esayread.data.Book
import com.esayread.data.BookFormat
import com.esayread.data.ScanResultHolder
import com.esayread.ui.theme.EsayReadTheme
import com.esayread.utils.FileScanner
import com.esayread.utils.BookManager
import androidx.navigation.NavController
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BookshelfScreen(
    navController: NavController,
    modifier: Modifier = Modifier,
    onBookClick: (Book) -> Unit = {}
) {
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()
    val fileScanner = remember { FileScanner(context) }
    val bookManager = remember { BookManager(context) }
    
    // 书籍列表状态
    var books by remember { mutableStateOf<List<Book>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var showPermissionDialog by remember { mutableStateOf(false) }
    var showDeleteDialog by remember { mutableStateOf(false) }
    var bookToDelete by remember { mutableStateOf<Book?>(null) }
    var searchQuery by remember { mutableStateOf("") }
    var isSearchActive by remember { mutableStateOf(false) }
    
    // 过滤后的书籍列表
    val filteredBooks = remember(books, searchQuery) {
        if (searchQuery.isBlank()) {
            books
        } else {
            books.filter { book ->
                book.title.contains(searchQuery, ignoreCase = true) ||
                book.author.contains(searchQuery, ignoreCase = true)
            }
        }
    }
    
    // 加载已存在的书籍
    LaunchedEffect(Unit) {
        try {
            val existingBooks = bookManager.getExistingBooks()
            books = existingBooks
            Log.d("BookshelfScreen", "Loaded ${existingBooks.size} existing books")
        } catch (e: Exception) {
            Log.e("BookshelfScreen", "Error loading existing books", e)
        }
    }
    
    // 监听页面重新进入，刷新书架
    DisposableEffect(navController.currentBackStackEntry) {
        val currentBackStackEntry = navController.currentBackStackEntry
        if (currentBackStackEntry?.destination?.route == "bookshelf") {
            // 每次进入书架页面都刷新书籍列表
            coroutineScope.launch {
                try {
                    val existingBooks = bookManager.getExistingBooks()
                    books = existingBooks
                    Log.d("BookshelfScreen", "Refreshed bookshelf with ${existingBooks.size} books on page enter")
                } catch (e: Exception) {
                    Log.e("BookshelfScreen", "Error refreshing bookshelf on page enter", e)
                }
            }
        }
        onDispose { }
    }
    
    // 权限请求
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        val allGranted = permissions.values.all { it }
        Log.d("BookshelfScreen", "Permission result: $permissions, all granted: $allGranted")
        if (allGranted) {
            // 权限已授予，开始扫描
            coroutineScope.launch {
                isLoading = true
                Log.d("BookshelfScreen", "Starting lazy book scan after permission grant...")
                try {
                    val scannedBooks = mutableListOf<Book>()
                    
                    fileScanner.scanAllBooksLazy(
                        onBookFound = { book ->
                            // 只记录扫描到的书籍，不添加到书架显示
                            scannedBooks.add(book)
                            Log.d("BookshelfScreen", "Found book during scan: ${book.title}")
                        },
                        onScanComplete = { finalBooks ->
                            Log.d("BookshelfScreen", "Lazy scan completed. Final count: ${finalBooks.size} books")
                            
                            // 无论是否有书籍都跳转到选择页面，让用户看到扫描结果
                            ScanResultHolder.setScannedBooks(finalBooks)
                            navController.navigate("book_selection")
                            Log.d("BookshelfScreen", "跳转到书籍选择界面，共 ${finalBooks.size} 本书可选择")
                            
                            isLoading = false
                            Log.d("BookshelfScreen", "Lazy book scan completed after permission grant")
                        }
                    )
                } catch (e: Exception) {
                    Log.e("BookshelfScreen", "Error during lazy book scan after permission grant", e)
                    e.printStackTrace()
                    isLoading = false
                }
            }
        } else {
            showPermissionDialog = true
        }
    }
    
    // 检查权限并扫描文件
    fun scanBooks() {
        // 检查 MANAGE_EXTERNAL_STORAGE 权限（Android 11+）
        val hasManagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            Environment.isExternalStorageManager()
        } else {
            // Android 10 及以下检查基础存储权限
            ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        }
        
        Log.d("BookshelfScreen", "MANAGE_EXTERNAL_STORAGE permission: $hasManagePermission")
        
        if (hasManagePermission) {
            // 立即跳转到选择页面，开始懒加载扫描
            Log.d("BookshelfScreen", "权限已授予，立即跳转到扫描页面")
            ScanResultHolder.clearScannedBooks() // 清空之前的扫描结果
            navController.navigate("book_selection")
        } else {
            // 需要跳转到设置页面授予权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                Log.d("BookshelfScreen", "Requesting MANAGE_EXTERNAL_STORAGE permission...")
                try {
                    val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                    intent.data = Uri.parse("package:${context.packageName}")
                    context.startActivity(intent)
                } catch (e: Exception) {
                    Log.e("BookshelfScreen", "Failed to open settings", e)
                    showPermissionDialog = true
                }
            } else {
                // Android 10 及以下请求基础存储权限
                Log.d("BookshelfScreen", "Requesting basic storage permission...")
                val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
                permissionLauncher.launch(permissions)
            }
        }
    }
    
    // 权限对话框
    if (showPermissionDialog) {
        AlertDialog(
            onDismissRequest = { showPermissionDialog = false },
            title = { Text("需要存储权限") },
            text = { Text("应用需要访问存储权限来扫描您设备上的电子书文件。\n\n对于Android 11+设备，请在设置中授予'所有文件访问权限'。") },
            confirmButton = {
                TextButton(
                    onClick = { showPermissionDialog = false }
                ) {
                    Text("确定")
                }
            }
        )
    }

    Column(
        modifier = modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 16.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "我的书架",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Text(
                    text = "共 ${filteredBooks.size} 本书",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                
                // 搜索按钮
                IconButton(
                    onClick = { isSearchActive = !isSearchActive }
                ) {
                    Icon(
                        imageVector = Icons.Filled.Search,
                        contentDescription = "搜索",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
                
                // 调试扫描按钮
                IconButton(
                    onClick = { 
                        Log.d("BookshelfScreen", "=== 手动触发调试扫描 ===")
                        scanBooks() 
                    },
                    enabled = !isLoading
                ) {
                    if (isLoading) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp
                        )
                    } else {
                        Icon(
                            imageVector = Icons.Filled.Refresh,
                            contentDescription = "调试扫描",
                            tint = MaterialTheme.colorScheme.error
                        )
                    }
                }
            }
        }
        
        // 搜索框
        if (isSearchActive) {
            OutlinedTextField(
                value = searchQuery,
                onValueChange = { searchQuery = it },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(bottom = 16.dp),
                placeholder = { Text("搜索书名或作者...") },
                leadingIcon = {
                    Icon(
                        imageVector = Icons.Filled.Search,
                        contentDescription = "搜索"
                    )
                },
                trailingIcon = {
                    if (searchQuery.isNotEmpty()) {
                        IconButton(
                            onClick = { searchQuery = "" }
                        ) {
                            Icon(
                                imageVector = Icons.Filled.Clear,
                                contentDescription = "清除"
                            )
                        }
                    }
                },
                singleLine = true,
                shape = RoundedCornerShape(12.dp)
            )
        }

        // 内容区域
        if (filteredBooks.isEmpty() && !isLoading) {
            // 空状态
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(32.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Icon(
                    imageVector = Icons.Filled.Book,
                    contentDescription = null,
                    modifier = Modifier.size(64.dp),
                    tint = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(16.dp))
                Text(
                    text = "书架空空如也",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "点击下方按钮扫描设备中的电子书",
                    fontSize = 14.sp,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(24.dp))
                Button(
                    onClick = { scanBooks() },
                    enabled = !isLoading
                ) {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = null,
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("扫描电子书")
                }
            }
        } else {
            // 书籍网格
            LazyVerticalGrid(
                columns = GridCells.Adaptive(minSize = 140.dp),
                contentPadding = PaddingValues(16.dp),
                horizontalArrangement = Arrangement.spacedBy(16.dp),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 添加按钮项
                item {
                    AddBookItem(
                        onClick = { scanBooks() },
                        isLoading = isLoading
                    )
                }
                
                // 书籍项
                items(filteredBooks) { book ->
                    BookItem(
                        book = book,
                        onClick = { onBookClick(book) },
                        onLongClick = {
                            bookToDelete = book
                            showDeleteDialog = true
                        }
                    )
                }
            }
        }
    }
    
    // 删除确认对话框
    if (showDeleteDialog && bookToDelete != null) {
        AlertDialog(
            onDismissRequest = {
                showDeleteDialog = false
                bookToDelete = null
            },
            title = {
                Text("删除书籍")
            },
            text = {
                Text("确定要删除《${bookToDelete!!.title}》吗？\n\n此操作将同时删除书籍文件和相关数据（笔记、阅读进度等），且无法恢复。")
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        coroutineScope.launch {
                            try {
                                val success = bookManager.deleteBook(bookToDelete!!)
                                if (success) {
                                    // 从列表中移除已删除的书籍
                                    books = books.filter { it.id != bookToDelete!!.id }
                                    Log.d("BookshelfScreen", "Successfully deleted book: ${bookToDelete!!.title}")
                                } else {
                                    Log.e("BookshelfScreen", "Failed to delete book: ${bookToDelete!!.title}")
                                }
                            } catch (e: Exception) {
                                Log.e("BookshelfScreen", "Error deleting book: ${bookToDelete!!.title}", e)
                            } finally {
                                showDeleteDialog = false
                                bookToDelete = null
                            }
                        }
                    }
                ) {
                    Text("删除", color = MaterialTheme.colorScheme.error)
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showDeleteDialog = false
                        bookToDelete = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }
}

@Composable
fun AddBookItem(
    onClick: () -> Unit,
    isLoading: Boolean,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .width(140.dp)
            .clickable { if (!isLoading) onClick() },
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        )
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // 封面区域 - 与BookItem保持一致的宽高比 3:4
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(3f / 4f)
                    .clip(RoundedCornerShape(6.dp))
                    .background(MaterialTheme.colorScheme.surface),
                contentAlignment = Alignment.Center
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(32.dp),
                        strokeWidth = 3.dp
                    )
                } else {
                    Icon(
                        imageVector = Icons.Filled.Add,
                        contentDescription = "添加书籍",
                        modifier = Modifier.size(48.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 标题
            Text(
                text = if (isLoading) "扫描中..." else "扫描电子书",
                fontSize = 12.sp,
                fontWeight = FontWeight.Medium,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                color = if (isLoading) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.primary
            )
            
            if (!isLoading) {
                Spacer(modifier = Modifier.height(4.dp))
                
                // 支持格式
                Text(
                    text = "EPUB/PDF/MOBI",
                    fontSize = 10.sp,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun BookItem(
    book: Book,
    onClick: () -> Unit,
    onLongClick: () -> Unit = {},
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .width(140.dp)
            .combinedClickable(
                onClick = { onClick() },
                onLongClick = { onLongClick() }
            ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(8.dp)
    ) {
        Column(
            modifier = Modifier.padding(12.dp)
        ) {
            // 书籍封面 - 固定宽高比 3:4
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(3f / 4f)
                    .clip(RoundedCornerShape(6.dp))
                    .background(MaterialTheme.colorScheme.surfaceVariant),
                contentAlignment = Alignment.Center
            ) {
                if (book.coverPath != null && File(book.coverPath).exists()) {
                    AsyncImage(
                        model = ImageRequest.Builder(LocalContext.current)
                            .data(book.coverPath)
                            .crossfade(true)
                            .build(),
                        contentDescription = "书籍封面",
                        modifier = Modifier.fillMaxSize(),
                        contentScale = ContentScale.Crop
                    )
                } else {
                    Icon(
                        imageVector = Icons.Filled.Book,
                        contentDescription = "书籍封面",
                        modifier = Modifier.size(48.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 书名
            Text(
                text = book.title,
                fontSize = 12.sp,
                fontWeight = FontWeight.Medium,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
                color = MaterialTheme.colorScheme.onSurface
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 作者
            Text(
                text = book.author,
                fontSize = 10.sp,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 格式标签
            Surface(
                shape = RoundedCornerShape(4.dp),
                color = when (book.format) {
                    BookFormat.EPUB -> Color(0xFF4CAF50)
                    BookFormat.PDF -> Color(0xFF2196F3)
                    BookFormat.MOBI -> Color(0xFFFF9800)
                },
                modifier = Modifier.wrapContentSize()
            ) {
                Text(
                    text = book.format.name,
                    fontSize = 9.sp,
                    color = Color.White,
                    modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp)
                )
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun BookshelfScreenPreview() {
    EsayReadTheme {
        // BookshelfScreen() // 预览时无法提供NavController，暂时注释
    }
}

@Preview(showBackground = true)
@Composable
fun BookItemPreview() {
    EsayReadTheme {
        BookItem(
            book = Book(
                id = "1",
                title = "三体",
                author = "刘慈欣",
                filePath = "/storage/books/threebody.epub",
                fileSize = 1024000,
                format = BookFormat.EPUB,
                addTime = System.currentTimeMillis()
            ),
            onClick = {}
        )
    }
}